#include "adalog/LogLevel.h"
#include "adalog/Logger.h"
#include "adalog/appender/AsyncRollFileAppender.h"
#include <atomic>
#include <chrono>
#include <filesystem>
#include <memory>
#include <thread>
#include <vector>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char** argv)
{

    std::chrono::system_clock::time_point begin;
    std::chrono::system_clock::time_point end0;
    std::chrono::system_clock::time_point end1;
    double avg_add_request_time = 0;
    {
        fs::path log_file = fs::canonical(fs::path(argv[0])).parent_path() / "logs" / "bustub";
        // 使用LoggerBuilder创建一个新的Logger
        auto logger= std::make_unique<adalog::LoggerBuilder>()
                            ->BuildLoggerName("async_logger")
                                .BuildLogLevel(adalog::LogLevel::WARN)
                                .BuildAppender(std::make_shared<adalog::AsyncRollFileAppender>(log_file, 4 * 1024 * 1024))
                                .BuildLogger();

        std::atomic<bool> end{false};
        std::vector<std::thread> threads;
        int thread_num = 5;
        std::atomic<int> count{100000};
        std::mutex mtx;

        begin = std::chrono::system_clock::now();
        for (int i = 0; i < thread_num; ++i)
        {
            threads.emplace_back([&](){
                while(count.fetch_sub(1) > 0)
                {
                    auto begin = std::chrono::system_clock::now();
                    logger->Error("Error", __FILE__, __LINE__);
                    auto end = std::chrono::system_clock::now();
                    auto ms= std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();
                    {
                        std::unique_lock<std::mutex> lock(mtx);
                        avg_add_request_time = (avg_add_request_time + ms) / 2.0;
                    }
                }
            });
        }
        for (auto& t : threads)
        {
            t.join();
        }
        end0 = std::chrono::system_clock::now();
    }
    end1 = std::chrono::system_clock::now();
    auto ms= std::chrono::duration_cast<std::chrono::milliseconds>(end0 - begin).count();
    ADALOG_DEFAULT_DEBUG("end0： " + std::to_string(ms) + " ms.");
    ms= std::chrono::duration_cast<std::chrono::milliseconds>(end1 - begin).count();
    ADALOG_DEFAULT_DEBUG("end1： " + std::to_string(ms) + " ms.");

    ADALOG_DEFAULT_DEBUG("平均添加一个日志事件需要： " + std::to_string(avg_add_request_time) + " 纳秒.");
    return 0;
}